package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusRequest;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusResponse;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.DeviceDataByDayVo;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.MyElderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 老人家属Service业务层处理
 * 
 * @author alexis
 * @date 2025-01-09
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private Client client;
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }

    /**
     * 小程序登录方法
     *
     * @param userLoginRequestDto 请求数据
     * @return 登录结果，包含token和nickname
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1.调用微信官方接口获取openId
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());

        // 2.根据openId查询数据库获取用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));

        // 3.如果用户信息不存在，就创建一个用户，并绑定openId
        if (ObjectUtils.isEmpty(familyMember)) {
            // 新用户
            familyMember = new FamilyMember();
            familyMember.setOpenId(openId);
        }

        // 4.调用微信接口获取手机号
        String phoneNumber = wechatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        // 不论是新用户还是老用户，都更新手机号
        familyMember.setPhone(phoneNumber);

        // 5.保存或更新用户，如果是新增，要生成一个用户名
        saveOrUpdateFamilyMember(familyMember);

        // 6.封装用户信息到token中，返回给小程序
        LoginVo loginVo = new LoginVo();
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        String token = tokenService.createToken(claims);
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        // 返回结果
        return loginVo;
    }

    /**
     * 新增或更新老人家属
     * @param familyMember  老人家属对象
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember) {
        // 判断id是否为空
        if (ObjectUtils.isEmpty(familyMember.getId())) {
            // 新增
            // 生成一个随机的用户名，规则是：一个随机的好听的名字+手机号后4位
            String prefix = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()));
            String nickName = prefix + familyMember.getPhone().substring(7);
            familyMember.setName(nickName);
            familyMemberMapper.insert(familyMember);
        } else {
            // 更新
            familyMemberMapper.updateById(familyMember);
        }
    }

    /**
     * 家属绑定老人
     *
     * @param bindingElderDto 老人的姓名，身份证，称呼
     */
    @Override
    public void bindingElder(BindingElderDto bindingElderDto) {
        //通过姓名和身份证查询老人
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getName, bindingElderDto.getName())
                .eq(Elder::getIdCardNo, bindingElderDto.getIdCard())
                .in(Elder::getStatus, 1, 2, 4));
        //如果没有，抛异常，无此老人
        if (ObjectUtils.isEmpty(elder)){
            throw new BaseException("未查询到该老人");
        }
        //查到后保存
        //家属id
        Long familyId = UserThreadLocal.get();
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setFamilyMemberId(familyId);
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setRemark(bindingElderDto.getRemark());
        familyMemberElder.setCreateBy(String.valueOf(familyId));
        familyMemberElder.setUpdateBy(String.valueOf(familyId));
        familyMemberElderMapper.insert(familyMemberElder);
    }

    /**
     * 根据家属id查询绑定的老人列表
     *
     * @return 查询到的老人列表
     */
    @Override
    public List<MyElderVo> MyElders() {
        Long fid = UserThreadLocal.get();
        return familyMemberElderMapper.getMyElders(fid);
    }

    /**
     * 分页查询家人绑定的老人列表
     *
     * @param dto pageNum  pageSize
     * @return
     */
    @Override
    public List<FamilyMemberElderVo> listByPage(ElderDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        Long mid = UserThreadLocal.get();
        Page<FamilyMemberElderVo> re=familyMemberElderMapper.selectElderInfo(mid);
        List<FamilyMemberElderVo> result = re.getResult();
        return result;
    }

    /**
     * 查询老人健康数据
     *
     * @param dto deviceName , productKey
     * @return
     */
    @Override
    public AjaxResult deviceDataInfo(DeviceDto dto) {
        QueryDevicePropertyStatusRequest request = new QueryDevicePropertyStatusRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setDeviceName(dto.getDeviceName());
        request.setProductKey(dto.getProductKey());
        QueryDevicePropertyStatusResponse response;
        try {
             response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!response.body.success){
            throw new BaseException("从IOT平台查询数据失败");
        }
        return AjaxResult.success(response.body.data);
    }

    /**
     * 根据小时段，查询指定功能数据
     *
     * @param dto
     * @return
     */
    @Override
    public List<DeviceDataByDayVo> queryDeviceDataListByDay(DeviceDataByDayDto dto) {
        LocalDateTime start = LocalDateTimeUtil.of(dto.getStartTime()).toLocalDate().atStartOfDay();
        LocalDateTime end = start.plusDays(1);
        List<DeviceDataByDayVo> list= deviceDataMapper.queryDeviceDataListByDay(dto,start,end);
        return list;
    }

    /**
     * 根据天数，查询指定功能数据
     *
     * @param dto
     * @return
     */
    @Override
    public List<DeviceDataByDayVo> queryDeviceDataListByWeek(DeviceDataByDayDto dto) {
        /*
        方法一：通过数据递归表，两表联合获取
        LocalDateTime start = LocalDateTimeUtil.of(dto.getStartTime());
        LocalDateTime end = LocalDateTimeUtil.of(dto.getEndTime());
        List<DeviceDataByDayVo> list=deviceDataMapper.queryDeviceDataListByWeek(dto,start,end);
        return list;
        */
        //方法二；业务层实现
        LocalDateTime start = LocalDateTimeUtil.of(dto.getStartTime());
        LocalDateTime end = LocalDateTimeUtil.of(dto.getEndTime());
        List<DeviceDataByDayVo> list=deviceDataMapper.Week(dto,start,end);
          List<DeviceDataByDayVo> allDay = new ArrayList<>();

            while (start.isBefore(end)){
                DeviceDataByDayVo day = new DeviceDataByDayVo();
                String d = start.format(DateTimeFormatter.ofPattern("MM.dd")).toString();
                day.setDateTime(d);
                day.setDataValue(0.0);
                start=start.plusDays(1);
                allDay.add(day);
            }
            allDay.forEach(day->{
                list.forEach(ls->{
                    if (day.getDateTime().equals(ls.getDateTime())){
                        day.setDataValue(ls.getDataValue());
                    }
                });
            });

        return allDay;
    }
}
